﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FDSimpleModelGenerator.Logging;
using FDSimpleModelGenerator.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

namespace FDSimpleModelGenerator
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            context.Result = new JsonResult(ApiResult.Failure(ApiResultCode.Exception, context.Exception.Message));
            var log = context.HttpContext.RequestServices.GetService<ILog<GlobalExceptionFilterAttribute>>();
            log.Error(GetErrorMsg(context.Exception));
            return base.OnExceptionAsync(context);
        }

        private string GetErrorMsg(Exception e)
        {
            var sb = new StringBuilder();
            do
            {
                sb.Append($"{e.Message}:{e.Source},{e.StackTrace}\r\n");
                e = e.InnerException;
            } while (e != null);

            return sb.ToString();
        }
    }
}
